package web.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {
	final static int PROT = 7788;
	private static ExecutorService executorService;

	public static void main(String[] args) throws IOException {
		ServerSocket server = null;
		server = new ServerSocket(PROT);
		System.out.println(" server start .. ");
		//Socket socket=null;
		// 进行阻塞
		
		/**
		 * 线程过多会压死服务器
		 */
		
		/*while(true) {
			Socket socket = server.accept();
			// 新建一个线程执行客户端的任务
			System.out.println("************");
			new Thread(new ServerHandler(socket)).start();
		}
		*/
		 
		/**
		 * 采用线程池的方式，能避免这一个问题
		 */
		createThreadPool();
        while(true){
        	Socket  socket = server.accept();
        	executorService.execute(new ServerHandler(socket));
        }
		
	}
	
	private synchronized static void createThreadPool() {
	//	executorService=Executors.newFixedThreadPool(10);
		if (executorService != null)
			return;

		BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(150);
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 1000, 10L, TimeUnit.SECONDS, queue);
		threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {

			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				try {
					executor.getQueue().put(r);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});

		executorService = threadPool;
	}
}

class ServerHandler implements Runnable {

	private Socket socket;

	public ServerHandler(Socket socket) {
		this.socket = socket;
	}

	
	public void run() {
		BufferedReader in = null;
		PrintWriter out = null;
		try {
			in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			out = new PrintWriter(this.socket.getOutputStream(), true);
			String body = null;
			while (true) {
				body = in.readLine();
				if (body == null)
					break;
				System.out.println("Server :" + body);
				out.println("服务器端回送响的应数据."+new Random().nextInt());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}


